package cn.ubeta.b2c.opengl;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.MotionEvent;

class SphereSurfaceView extends GLSurfaceView {

    private EarthRenderer mOpenGLRenderer;
    float lastX, lastY;

    private int mode = 0;

    float oldDist = 0;

    public SphereSurfaceView(Context context) {
        this(context, null);
    }

    public SphereSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        //setEGLContextClientVersion(2); //设置使用OPENGL ES2.0
        mOpenGLRenderer = new EarthRenderer(context);
        setRenderer(mOpenGLRenderer);
        //setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); // 设置渲染模式为主动渲染
        new Thread(() -> {
            while (mOpenGLRenderer != null) {
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                }
                rotate(2, 2);
            }
        }).start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                mode = 1;
                lastX = event.getRawX();
                lastY = event.getRawY();
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mode += 1;
                oldDist = caluDist(event);
                break;
            case MotionEvent.ACTION_POINTER_UP:
                mode -= 1;
                break;
            case MotionEvent.ACTION_UP:
                mode = 0;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode >= 2) {
                    float newDist = caluDist(event);
                    if (Math.abs(newDist - oldDist) > 2f) {
                        mOpenGLRenderer.zoom(newDist, oldDist);
                    }
                } else {
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;
                    rotate(dx, dy);
                }
                break;
        }

        lastX = (int) event.getRawX();
        lastY = (int) event.getRawY();
        return true;
    }

    private void rotate(float xOffset, float yOffset) {
        if (mOpenGLRenderer != null) {
            mOpenGLRenderer.rotate(xOffset, yOffset);
        }
    }

    public float caluDist(MotionEvent event) {
        float dx = event.getX(0) - event.getX(1);
        float dy = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(dx * dx + dy * dy);
    }
}